package com.jxl.domain.service.impl;

import com.google.common.cache.Cache;
import com.jxl.common.enums.CategoryTypeCodeEnum;
import com.jxl.common.enums.DeletedCodeEnum;
import com.jxl.domain.convert.SubjectCategoryConvert;
import com.jxl.domain.convert.SubjectLabelConvert;
import com.jxl.domain.entity.SubjectLabelBO;
import com.jxl.domain.util.CacheUtil;
import com.jxl.infra.basic.entity.SubjectCategory;
import com.jxl.infra.basic.entity.SubjectLabel;
import com.jxl.infra.basic.entity.SubjectMapping;
import com.jxl.infra.basic.service.SubjectCategoryService;
import com.jxl.domain.entity.SubjectCategoryBO;
import com.jxl.domain.service.SubjectCategoryDomainService;
import com.jxl.infra.basic.service.SubjectLabelService;
import com.jxl.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor poolExecutor;

    @Resource
    private CacheUtil cacheUtil;


    /**
     * 添加题目分类
     * @param subjectCategoryBO
     */
    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConvert.
                INSTANCE.convertBoToSubjectCategory(subjectCategoryBO);
        subjectCategoryService.insert(subjectCategory);
    }

    /**
     * 查询大分类
     * @return
     */
    @Override
    public List<SubjectCategoryBO> getQueryPrimaryCategory() {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setCategoryType(CategoryTypeCodeEnum.PAMARY.getCode());
        List<SubjectCategory> list = subjectCategoryService.list(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOS =
                SubjectCategoryConvert.INSTANCE.convertToSubjectCategoryList(list);
        subjectCategoryBOS.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return subjectCategoryBOS;

    }

    @Override
    public List<SubjectCategoryBO> queryCategoryByPrimary(Long id) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(id);
        subjectCategory.setCategoryType(CategoryTypeCodeEnum.SECONDE.getCode());
        List<SubjectCategory> list = subjectCategoryService.list(subjectCategory);
        List<SubjectCategoryBO> subjectCategoryBOS =
                SubjectCategoryConvert.INSTANCE.convertToSubjectCategoryList(list);
        return subjectCategoryBOS;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory =
                SubjectCategoryConvert.INSTANCE.convertBoToSubjectCategory(subjectCategoryBO);
        Integer update = subjectCategoryService.update(subjectCategory);
        return update>0;
    }

    @Override
    public Boolean delete(Long id) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setId(id);
        subjectCategory.setIsDeleted(DeletedCodeEnum.DELETE.getCode());
        Integer update = subjectCategoryService.update(subjectCategory);
        return update>0;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        String key  = "queryCategoryAndLabel."+subjectCategoryBO.getId();
        List<SubjectCategoryBO> array = cacheUtil.getArray(key, SubjectCategoryBO.class, s -> getSubjectCategoryBOS(subjectCategoryBO));
        return array;
    }

    /**
     * 构建数据库查询层
     * @param subjectCategoryBO
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @SneakyThrows
    private List<SubjectCategoryBO> getSubjectCategoryBOS(SubjectCategoryBO subjectCategoryBO){
        //查询出所有的小分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(subjectCategoryBO.getId());
        subjectCategory.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
        List<SubjectCategory> twoCategory = subjectCategoryService.queryCategory(subjectCategory);
        //线程处理
        List<FutureTask<Map<Long,List<SubjectLabelBO>>>> futureTaskList = new LinkedList<>();
        //根据每一个小分类去查询标签
        twoCategory.forEach(cate->{
            FutureTask<Map<Long, List<SubjectLabelBO>>> mapFutureTask = new FutureTask<>(() ->
                    getSubjectCategoryBO(cate)
            );
            futureTaskList.add(mapFutureTask);
            poolExecutor.submit(mapFutureTask);
        });
        //处理完以后进行值的提取
        Map<Long, List<SubjectLabelBO>> map = new HashMap<>();
        for (FutureTask<Map<Long, List<SubjectLabelBO>>> mapFutureTask : futureTaskList) {
            Map<Long, List<SubjectLabelBO>> longListMap = mapFutureTask.get();
            if (map==null) continue;
            map.putAll(longListMap);
        }
        //类型转换
        List<SubjectCategoryBO> list1 = SubjectCategoryConvert.INSTANCE.
                convertToSubjectCategoryList(twoCategory);
        list1.forEach(t->{
            List<SubjectLabelBO> labelBOS = map.get(t.getId());
            if (labelBOS!=null){
                t.setLabelBOList(labelBOS);
            }
        });
        return list1;
    }

    private Map<Long,List<SubjectLabelBO>> getSubjectCategoryBO(SubjectCategory cate) {
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(cate.getId());
        subjectMapping.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelId(subjectMapping);
        //再查询出标签
        List<Long> labelIds = subjectMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = labelIds.size()==0? null :subjectLabelService.queryByIds(labelIds);
        //类型转换
        List<SubjectLabelBO> labelBOS = SubjectLabelConvert.INSTANCE.
                convertToSubjectLabelList(labelList);
        SubjectCategoryBO subjectCategoryBO1 = SubjectCategoryConvert.INSTANCE.
                convertToSubjectCategoryBO(cate);
        subjectCategoryBO1.setLabelBOList(labelBOS);
        map.put(cate.getId(),labelBOS);
        return map;
    }

}
